#include <stdio.h>
#include <stdlib.h>
#include "strset.h"
#include <assert.h>

#define T Strset_T

struct T {
    T next;
    char str[1];
};

T Strset_new(void){
    T set = calloc(1, sizeof *set);
    assert(set);
    return set;
}

void Strset_add(T set, char *str){
    T p = set;
    assert(set);
    assert(str);
    if(!Strset_member(set, str))
    {
        p = malloc(sizeof *p + strlen(str));
        assert(p);
        strcpy(p->str, str);
        p->next = set->next;
        set->next = p;
    }
    
}

void Strset_free(T *set)
{
	int i;
	assert(set && *set);
        T q, p;
        
        p = *set;
	while((q=p->next)!=NULL)
        {
            free(q);
            p=p->next;
        }
	free(*set);
	*set=NULL;
}

int Strset_member(T set, char *str){
    T p = set;
    while((p=p->next)!=NULL){
        if(strcmp(p->str, str)==0) return 1;
    }
    return 0;
}

int Strset_size(T set){
    T p = set;
    int c=0;
    while((p=p->next)!=NULL){
      ++c;
    }
    return c;
}

void Strset_foreach(T set, void apply(char *str, void *cl), void *cl){
    assert(set);
    assert(apply);
    while((set= set->next) != NULL)
         apply(set->str, cl);
}

